package controllers

import (
	"TeacherManager/common"
	"TeacherManager/models"
	"errors"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

/**
* Created by LONG  on 2018/5/28.
 */

func GetPubClasses(c *gin.Context) {
	examid := c.PostForm("examid")
	id := common.String_2_int(examid)
	//[{id: 0, text: '简单'}, {id: 1, text: '中等'}, {id: 2, text: '困难'}]
	exam := &models.Exam{
		ExamID: uint(id),
	}
	classes, err := exam.GetClassByExamId()

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"succeed": false,
			"message": "获取失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"succeed": true,
		"message": "获取成功",
		"classes": classes,
	})
}
func UpdateClass(c *gin.Context) {
	classname := c.PostForm("classname")
	classdescri := c.PostForm("classdescri")
	classinvitecode := c.PostForm("invitecode")
	cid := common.String_2_int(c.PostForm("cid"))
	classdescri = strings.TrimSpace(classdescri)
	classname = strings.TrimSpace(classname)

	class := &models.Class{
		ClassID:     uint(cid),
		ClassName:   classname,
		InviteCode:  classinvitecode,
		ClassDescri: classdescri,
	}
	var err error
	if len(class.ClassName) == 0 || len(class.InviteCode) == 0 {
		err = errors.New("班级名称和邀请码都不能为空")
	} else {

		err = class.UpdateClass()
		if err == nil {
			c.JSON(http.StatusOK, gin.H{
				"succeed": true,
				"message": "更改成功",
				"class":   class,
			})
			return
		} else {
			err = errors.New(" 数据库异常 更改失败")
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"succeed": false,
		"message": err.Error(),
	})
}

func GetClasses(c *gin.Context) {
	user, _ := c.Get(CONTEXT_USER_KEY)
	u, _ := user.(*models.User)
	//[{id: 0, text: '简单'}, {id: 1, text: '中等'}, {id: 2, text: '困难'}]
	classes := make([]common.Classmsg, 0)
	class, err := models.ListAllClass(u.ID)
	for _, val := range class {
		var class common.Classmsg = common.Classmsg{
			ID:   int(val.ClassID),
			Text: val.ClassName,
		}
		classes = append(classes, class)
	}
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"succeed": false,
			"message": "获取失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"succeed": true,
		"message": "获取成功",
		"classes": classes,
	})
}

//班级管理页面

func ManagerClass(c *gin.Context) {
	user, _ := c.Get(CONTEXT_USER_KEY)
	u, _ := user.(*models.User)
	classes, _ := models.ListAllClass(u.ID)

	c.HTML(http.StatusOK, "admin/managerclass.html", gin.H{
		"user":     user,
		"comments": models.MustListUnreadComment(),
		"classes":  classes,
	})
}
func CreateClass(c *gin.Context) {
	classname := c.PostForm("classname")
	fmt.Println(classname)
	classdescri := c.PostForm("classdescri")
	classinvitecode := c.PostForm("invitecode")
	var teacherid uint
	user, _ := c.Get(CONTEXT_USER_KEY)
	var tname string
	if user != nil {
		u, ok := user.(*models.User)
		if ok && u.IsAdmin {
			teacherid = u.ID
			tname = u.NickName
		}

	}

	class := &models.Class{
		ClassName:  classname,
		InviteCode: classinvitecode,
		TeacherID:  teacherid,
	}
	if len(strings.TrimSpace(classdescri)) != 0 {
		class.ClassDescri = classdescri
	}
	var err error
	if len(class.ClassName) == 0 || len(class.InviteCode) == 0 {
		err = errors.New("班级名称和邀请码都不能为空")
	} else {
		var id uint
		err, id = class.GetLastClassID()
		class.ClassLogo = fmt.Sprintf("logo%d.png", (id+1)%6)
		class.ClassColor = colors[(id+1)%11]
		err = class.Insert()
		if err == nil {
			c.JSON(http.StatusOK, gin.H{
				"succeed":  true,
				"message":  "建立成功",
				"class":    class,
				"nickname": tname,
			})
			return
		} else {
			err = errors.New("班级名称 已存在")
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"succeed": false,
		"message": err.Error(),
	})
}

func GetInviteCode(c *gin.Context) {
	isFirst := c.Query("isFirst")
	class := &models.Class{}

	if strings.Compare(isFirst, "true") == 0 {
		err, id := class.GetLastClassID()
		if err != nil {
			id = 1
		}
		invitecode := common.Krand(6, 3, id)
		fmt.Println(string(invitecode))
		c.JSON(http.StatusOK, gin.H{
			"succeed":    true,
			"message":    "获取成功",
			"invitecode": string(invitecode),
		})
		return
	}
	ClassID := c.PostForm("ClassID")
	id, err := strconv.Atoi(ClassID)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"succeed":    false,
			"message":    "获取失败",
			"invitecode": "",
		})
		return
	}
	invitecode := common.Krand(6, 3, uint(id))
	c.JSON(http.StatusOK, gin.H{
		"succeed":    true,
		"message":    "建立成功",
		"invitecode": string(invitecode),
	})

}
func SeeClass(c *gin.Context) {
	user, _ := c.Get(CONTEXT_USER_KEY)
	u, _ := user.(*models.User)
	classes, _ := models.ListAllClass(u.ID)

	for _, val := range classes {
		if len(val.ClassLogo) == 0 {
			val.ClassLogo = fmt.Sprintf("logo%d.png", val.ClassID%6)
			val.ClassColor = colors[val.ClassID%11]
		}
		if len([]rune(val.ClassDescri)) > 20 {
			val.ClassDescri = fmt.Sprintf("%s....", string([]rune(val.ClassDescri)[:20]))
		}
	}
	c.HTML(http.StatusOK, "admin/seeclass.html", gin.H{
		"user":     user,
		"comments": models.MustListUnreadComment(),
		"classes":  classes,
	})
}

func DeleteClass(c *gin.Context) {
	classid := c.PostForm("classid")
	fmt.Println(classid)
	pid, err := strconv.ParseUint(classid, 10, 64)
	if err == nil {
		class := &models.Class{}
		class.ClassID = uint(pid)
		err = class.DeleteClass()
		err = class.DeleteRelated()
		if err == nil {
			c.JSON(http.StatusOK, gin.H{
				"succeed": true,
				"message": "删除成功",
			})
			return
		}
	}
	c.AbortWithError(http.StatusInternalServerError, err)
}
